<script setup>
import { nextTick } from 'vue'
const props = defineProps(['note'])

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref(null)

// 按组名分组的人员 待选标签
const peoplesGroup = reactive({})

myPost("/relation/relations", { userToken: User.token }, data => {
  data.forEach((raw) => {
    if (raw.rGroup) {  // 组员
      if (Object.keys(peoplesGroup).indexOf(raw.rGroup) == -1) {
        peoplesGroup[raw.rGroup] = []
      }
      peoplesGroup[raw.rGroup].push(raw.rName)
    } else {
      let leftPeople = data.find(i => i.rId == raw.rFromId)
      while (!leftPeople.rGroup) leftPeople = data.find(i => i.rId == leftPeople.rFromId)
      peoplesGroup[leftPeople.rGroup].push(raw.rName)
    }
  })
})

// 点击删除按钮
const handleClose = (tag) => {
  props.note.notePeople.splice(props.note.notePeople.indexOf(tag), 1)
}

// 单击添加标签
const showInput = () => {
  inputVisible.value = true
  nextTick(() => { InputRef.value.input.focus() })
}

// 输入框回车或者失去焦点
const handleInputConfirm = () => {
  if (inputValue.value) {
    props.note.notePeople.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 待选标签
const addTag = (tag) => {
  if (tag) { props.note.notePeople.push(tag) }
}

</script>

<template>
  <div class="tags">
    人员:
    <el-tag v-for="tag in note.notePeople" :key="tag" closable @close="handleClose(tag)">{{ tag }}</el-tag>

    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" size="small" @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm" style="width:90px;" maxlength="20" />
    <el-button v-else size="small" @click="showInput" style="width:90px;">+ New People
    </el-button>

    <!-- 待选列表 -->
    <el-tabs type="border-card" v-if="Object.keys(peoplesGroup).length" style="margin-top: 3px;">
      <el-tab-pane v-for="(value, key) of peoplesGroup" :key="key" :label="key">
        <el-tag v-for="tag in value" :key="tag" @click.once="addTag(tag)">
          {{ tag }}
        </el-tag>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<style scoped lang="less">
.tags {
  line-height: 29px;
}

.el-tag {
  cursor: pointer;
  margin-right: 5px;
}

::v-deep(.el-tabs) {
  border-radius: 5px;
  overflow: hidden;
  opacity: 0.9;

  .el-tabs__item.is-top {
    height: 25px;
    line-height: 25px;
  }

  .el-tabs__content {
    padding: 0px 10px 5px;
  }

  .el-tabs__nav-prev,
  .el-tabs__nav-next {
    line-height: 25px;
  }
}
</style>